﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using AffordoPlugin.Helper;
using AffordoPlugin.Model;

namespace AffordoPlugin.ElectronicScale
{
	public class ElectronicScaleUtil
	{
		public delegate void ElectronicData(string data);

		public ElectronicData ElectronicDataDelegate = null;

		public List<string> GetPortNames()
		{
			var comProts =  SerialPort.GetPortNames();

			return comProts.ToList();
		}

		public bool Run(Message<ElectrinicSaleContent> message)
		{
			try
			{
				var portName = ConfigurationHelper.GetAppSettingValue("portName");
				var baudRate = ConfigurationHelper.GetAppSettingValue("baudRate");
				var dataBits = ConfigurationHelper.GetAppSettingValue("dataBits");

				portName = string.IsNullOrEmpty(message?.content?.device) ? portName : message.content.device;

				var serialPort = new SerialPort(portName, Convert.ToInt32(baudRate), Parity.None, Convert.ToInt32(dataBits), StopBits.One);
				serialPort.DataReceived += SerialPort_DataReceived;

				if(!serialPort.IsOpen)
				{
					serialPort.Open();
				}
				
				return true;
			}
			catch (Exception ex)
			{
				LogHelper.Error("ElectronicScale异常" + ex.Message + ex.InnerException?.Message ?? "");
				return false;
			}
			
		}

		private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
		{
			var port = sender as SerialPort;

			if (port != null)
			{
				var len = port.BytesToRead;
				byte[] bytes = new byte[len];

				port.Read(bytes, 0, len);

				var msg = Encoding.UTF8.GetString(bytes);

				if (port.IsOpen)
				{
					port?.Close();
					port?.Dispose();
				}

				var matches = Regex.Matches(msg, "[\\d(.\\d)?]+");

				var data = matches[matches.Count - 1].Value;

				ElectronicDataDelegate.Invoke(data);

			}
		}
	}
}
